package com.ruicar.afs.cloud.auth.config;

import com.ruicar.afs.cloud.auth.oauth2.AfsTokenSerializationStrategy;
import com.ruicar.afs.cloud.auth.oauth2.AfsTokenServices;
import com.ruicar.afs.cloud.auth.validater.AfsOauthRequestValidator;
import com.ruicar.afs.cloud.common.core.constant.SecurityConstants;
import com.ruicar.afs.cloud.common.core.holder.TransRequestContextHolder;
import com.ruicar.afs.cloud.common.core.security.component.AfsWebResponseExceptionTranslator;
import com.ruicar.afs.cloud.common.core.security.constant.SystemInnerConstants;
import com.ruicar.afs.cloud.common.core.security.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Fzero
 * @date 2019-01-22
 * 认证服务器配置
 */
@Configuration
@AllArgsConstructor
@EnableAuthorizationServer
@Slf4j
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
	private final DataSource dataSource;
	private final AfsUserDetailsService afsUserDetailsService;
	private final AuthenticationManager authenticationManager;
	private final RedisConnectionFactory redisConnectionFactory;
	private final AfsOauthConfig afsOauthConfig;
	private final AfsNoPassLoginService afsNoPassLoginService;
	private final StringRedisTemplate stringRedisTemplate;


	@Bean("afsClientDetailsService")
	public ClientDetailsService clientDetailsService(){
		AfsClientDetailsService clientDetailsService = new AfsClientDetailsService(dataSource);
		clientDetailsService.setSelectClientDetailsSql(SecurityConstants.DEFAULT_SELECT_STATEMENT);
		clientDetailsService.setFindClientDetailsSql(SecurityConstants.DEFAULT_FIND_STATEMENT);
		return clientDetailsService;
	}

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.withClientDetails(clientDetailsService());
	}

	@Override
	public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
		oauthServer
				.allowFormAuthenticationForClients()
				.checkTokenAccess("isAuthenticated()");
	}

	@Bean
	public AfsTokenServices ifsTokenServices() {
		AfsTokenServices tokenServices = new AfsTokenServices();
		tokenServices.setAuthenticationManager(authenticationManager);
		tokenServices.setTokenEnhancer(tokenEnhancer());
		tokenServices.setOneDeviceLogin(afsOauthConfig.isOneDeviceLogin());
		tokenServices.setTokenStore(tokenStore());
		tokenServices.setReuseRefreshToken(false);
		tokenServices.setSupportRefreshToken(true);
		tokenServices.setStringRedisTemplate(stringRedisTemplate);
		tokenServices.setClientDetailsService(clientDetailsService());
		PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
		provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceWrapper<PreAuthenticatedAuthenticationToken>(
				afsUserDetailsService));
		tokenServices
				.setAuthenticationManager(new ProviderManager(Arrays.<AuthenticationProvider>asList(provider)));
		return tokenServices;
	}

	@Bean
	public AfsOauthRequestValidator afsOauthRequestValidator(){
		AfsOauthRequestValidator afsOauthRequestValidator = new AfsOauthRequestValidator();
		afsOauthRequestValidator.setAfsNoPassLoginService(afsNoPassLoginService);
		return afsOauthRequestValidator;
	}
	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) {

		endpoints
				.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
				.tokenStore(tokenStore())
				.requestValidator(afsOauthRequestValidator())
				.tokenEnhancer(tokenEnhancer())
				.userDetailsService(afsUserDetailsService)
				.authenticationManager(authenticationManager)
				.reuseRefreshTokens(false)
				.tokenServices(ifsTokenServices())
				.exceptionTranslator(new AfsWebResponseExceptionTranslator());
	}


	@Bean
	public TokenStore tokenStore() {
		RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
		tokenStore.setSerializationStrategy(new AfsTokenSerializationStrategy());
		tokenStore.setPrefix(SecurityConstants._PREFIX + SecurityConstants.OAUTH_PREFIX);
		tokenStore.setAuthenticationKeyGenerator(new DefaultAuthenticationKeyGenerator() {
			@Override
			public String extractKey(OAuth2Authentication authentication) {
				AfsUser ifsUser = (AfsUser) authentication.getUserAuthentication().getPrincipal();
				if (afsOauthConfig.isOneDeviceLogin()&&!(StringUtils.equals(ifsUser.getUsername(), SystemInnerConstants.NO_PASS_USER)||StringUtils.equals(ifsUser.getUsername(), SystemInnerConstants.SYSTEM_ADMIN))) {
					return super.extractKey(authentication) + ":" + TransRequestContextHolder.getClientType().getClientId();
				} else {
					return super.extractKey(authentication) + ":"
							+ TransRequestContextHolder.getClientInfo().getTenantId()+":"
							+ TransRequestContextHolder.getClientType().getClientId()
							+ ":" + ifsUser.getSysAssign();
				}
			}
		});
		return tokenStore;
	}


	@Bean
	public TokenEnhancer tokenEnhancer() {
		return (accessToken, authentication) -> {
			final Map<String, Object> additionalInfo = new HashMap<>(8);
			AfsUser ifsUser = (AfsUser) authentication.getUserAuthentication().getPrincipal();
			additionalInfo.put("user_id", ifsUser.getId());
			additionalInfo.put("username", ifsUser.getUsername());
			additionalInfo.put("dept_id", ifsUser.getDeptId());
			additionalInfo.put("sys_assign", ifsUser.getSysAssign());
			additionalInfo.put("userRealName", ifsUser.getUserRealName());
			additionalInfo.put("tenant_id", ifsUser.getTenantId());
			((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
			return accessToken;
		};
	}
}
